package com.zyh.study.myForestDemoPlus;


import com.dtflys.forest.Forest;
import com.zyh.study.myForestDemoPlus.OrderEventDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

/**
 * @Classname OrderSSEDeal
 * @Description TODO()
 * @Date 2025-09-08 0:20
 * @Created by 86177
 */
@Component
public class OrderSSEDeal {

    private static final Logger logger = LoggerFactory.getLogger(OrderSSEDeal.class);
    // API 认证信息 - 实际项目中应从环境变量或配置文件中读取
    private static final String API_KEY_ID = "CK12643YAM8UFHA6L62I";
    private static final String API_SECRET_KEY = "geWlg29V86nGODx8105u8u1kcefbW7Hy2tGCeHaP";

    // Alpaca API 使用 Basic Auth 认证方式
    String credentials = API_KEY_ID + ":" + API_SECRET_KEY;
    String authHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
    public void subscribeToOrderStatus(LocalDate since, LocalDate until, String sinceId, String untilId, AlpacaSSEDeal sse) {
        String url = "https://broker-api.sandbox.alpaca.markets/v2/events/trades";
        Forest.get(url)
                .addQuery("since", since)
                .addQuery("until", until)
                .addQuery("since_id", sinceId)
                .addQuery("until_id", untilId)
                .addHeader("accept", "text/event-stream")
                // 添加认证头
                .addHeader("authorization", authHeader)
                .sse()
                .setOnOpen(sse::onSSEOpen)
                .setOnClose(sse::onSSEClose)
                .addOnData(sse::onMessage)
                .listen();
    }

    // 添加新方法
    public List<OrderEventDTO> fetchEventRange(String sinceId, String untilId) {
        String url = "https://broker-api.sandbox.alpaca.markets/v2/events/trades";

        // 实际API调用（伪代码）
    /*
    return Forest.get(url)
        .addQuery("since_id", sinceId)
        .addQuery("until_id", untilId)
        .addHeader("authorization", authHeader)
        .executeAsList(OrderEventDTO.class);
    */

        logger.info("Fetching events from {} to {}", sinceId, untilId);
        return Collections.emptyList();
    }
}
